import { Order, OrderItem, Shipment } from "@mallfoundry/order"
import * as _ from "lodash"
import { useEffect, useState } from "react"

export class OrderTableItem {
  public id: string = ""
  public name: string = ""
  public price: number = 0
  public quantity: number = 0
  public shippingStatus: boolean = false
  public shippingProvider: string = ""
  public trackingNumber: string = ""
  public discountTotalPrice: string = ""
  public subtotalAmount: string = ""
  public productId: string = ""
  public variantId: string = ""
}

function findShipment(shipments: Shipment[], item: OrderItem) : Shipment {
  const { productId: aProductId = "", variantId: aVariantId } = item
  return _.find(shipments, aShipment => {
    return _.find(aShipment.items, aItem => aItem.productId === aProductId && aItem.variantId === aVariantId) !== undefined
  }) as Shipment
}

export function useOrderTableItems(aOrder: Order): OrderTableItem[] {
  const [items, setItems] = useState([] as OrderTableItem[])
  useEffect(() => {
    const { shipments = [] } = aOrder
    const newItems = _.map(aOrder.items, item => {
      const shipment = findShipment(shipments, item)
      return _.assign(new OrderTableItem(), {
        id: item.id,
        name: item.name,
        price: item.price,
        quantity: item.quantity,
        discountTotalPrice: item.discountTotalPrice,
        subtotalAmount: item.subtotalAmount,
        shippingStatus: !_.isUndefined(shipment),
        shippingMethod: "快递",
        shippingProvider: shipment.shippingProvider,
        trackingNumber: shipment?.trackingNumber,
        productId: item.productId,
        variantId: item.variantId,
      })
    })
    setItems(newItems)
  }, [aOrder])
  return items
}
